import '../../pages/App.css';
import './Home.css'
import ClearSvg from '../../assets/clear.svg';
import HistorySvg from '../../assets/history.svg';
import Loading from '../../assets/loading.svg'
import ShuruIcon from '../../assets/shuru.svg'

import { IconSearch } from '@arco-design/web-react/icon';
import { Message, Modal, Input } from '@arco-design/web-react';
import {
    useRecoilValue,
    useRecoilState
} from 'recoil';

import { getChats, deleteChat } from '../../api/all'

import copy from 'copy-to-clipboard';
import { useNavigate } from "react-router-dom"
import { marked } from 'marked'

import axios from "axios";
import { useRef, useEffect, useState } from 'react'
import { currentAiChatState, chatList } from './store'


axios.defaults.headers.common['token'] = window.localStorage.getItem('token') || window.sessionStorage.getItem('token');;
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
function isEmpty(obj) {
    if (typeof obj === "undefined" || obj == null || obj.trim() == "") {
        return true;
    } else {
        return false;
    }
}
function Home() {

    const navigate = useNavigate();

    const [controller, setController] = useState(new AbortController());

    const currentChat = useRecoilValue(currentAiChatState);

    const [dialog, setDialog] = useRecoilState(chatList);

    const dialogRef = useRef();

    const [sendState, setSendState] = useState(true)

    const [visibleHisory, setVisibleHisory] = useState(false)

    const [history, setHistory] = useState([])

    const [historyGroup, setHistoryGroup] = useState({})

    const [visibleTips, setVisibleTips] = useState(false)

    const sendMsg = () => {
        if (!localStorage.getItem('token')) {
            navigate("/login")
            return
        }
        if (isEmpty(document.getElementById('myTextarea').value)) {
            return
        }
        setSendState(false)
        let ms = document.getElementById('myTextarea').value
        let msgObj = {
            role: 0,
            date: Date.now() + '',
            msg: ms
        }
        pushMsg(msgObj)

        document.getElementById('myTextarea').value = ''



        axios.post('/chat/chatalls/chat', {
            // axios.post('http://47.92.247.100:7000/chatalls/chat', {
            content: ms, robot_id: currentChat.id,
        }, { signal: controller.signal }).then(function (response) {
            let result = typeof (response.data?.result) === "string" ? response.data?.result : JSON.stringify(response.data?.result)
            pushMsg({
                role: 1,
                date: Date.now() + '',
                msg: response.data.code === 0 ? result : response.data?.message
            })
            setSendState(true)
        });
    }

    const cancelSend = () => {
        setSendState(true)
        controller.abort()
        setController(new AbortController())
        pushMsg({
            role: 1,
            date: Date.now() + '',
            msg: '您取消了请求！'
        })
    }

    const pushMsg = (msg) => {
        let currentAi = JSON.parse(JSON.stringify(currentChat))
        let list = JSON.parse(JSON.stringify(dialogRef.current))
        let log = list[currentChat.id]?.log || []
        if (msg.role === 0) {
            log.push({ ...msg })
            log.push({
                role: 2,
                date: new Date(),
                msg: '......'
            })
            currentAi.log = log
            list[currentAi.id] = currentAi
            setDialog(list)
        }
        if (msg.role === 1) {
            log.pop()
            const content = msg.msg
            let num = 0
            msg.msg = ''
            log.push({ ...msg })
            currentAi.log = log
            list[currentAi.id] = currentAi
            setDialog(list)

            const interval = setInterval(() => {
                currentAi = JSON.parse(JSON.stringify(currentChat))
                list = JSON.parse(JSON.stringify(dialogRef.current))
                log = list[currentChat.id]?.log || []
                num += 1
                log[log.length - 1].msg = content.substr(0, num)
                currentAi.log = log
                list[currentAi.id] = currentAi
                setDialog(list)
                if (num === content.length) {
                    clearInterval(interval)
                }
            }, 50);
        }

    }

    useEffect(() => {
        dialogRef.current = dialog;
        let $div = document.getElementById('scrollDiv');
        $div.scrollTop = $div.scrollHeight + 200;
    }, [dialog]);

    useEffect(() => {
        bindEnter()
        if (!localStorage.getItem('token')) {
            navigate("/login")
        }
    }, [])

    const bindEnter = (e) => {
        if (e && e.keyCode === 13 && e.shiftKey) {

        } else if (e && e.keyCode === 13) {
            // 阻止原生的换行事件
            e.preventDefault();
            // TODO: 发消息
            sendMsg()
        }
    }

    const copyText = (text) => {
        copy(text);
        Message.success('复制成功')
    }

    const copyHtml = ((text) => {
        return <svg stroke="currentColor" onClick={() => {
            copyText(text)
        }} fill="currentColor" strokeWidth="0" viewBox="0 0 512 512" className="self-top cursor-pointer invisible group-hover:visible mt-[12px] text-primary-text" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><rect width="336" height="336" x="128" y="128" fill="none" strokeLinejoin="round" strokeWidth="32" rx="57" ry="57"></rect><path fill="none" strokeLinecap="round" strokeLinejoin="round" strokeWidth="32" d="M383.5 128l.5-24a56.16 56.16 0 00-56-56H112a64.19 64.19 0 00-64 64v216a56.16 56.16 0 0056 56h24"></path></svg>
    })

    const loading = ((item) => {
        return (
            <div key={item.date} className="group flex gap-3 w-full flex-row mt-2">
                <div className="flex flex-col w-11/12  max-w-fit items-start gap-2">
                    <div className="px-4 py-2 w-full answer">
                        <span className="leading-tight" style={{ display: "inherit" }}>
                            {/* <Spin dot /> 我在思考中... */}
                            <img className='loading_xzy' src={Loading} alt='' />我在思考中...
                        </span>
                    </div>
                </div>
            </div>
        )
    })

    const clearHistoryLocal = (id) => {
        let lo = JSON.parse(JSON.stringify(dialog))
        lo[id].log = []
        setDialog(lo)
    }

    const clearHistory = () => {
        deleteChat({ id: currentChat.id }).then((res) => {
            if (res.code === 0) {
                Message.success('清除成功')
                clearHistoryLocal(currentChat.id)
            }
        })
    }

    const checkHistory = () => {
        setVisibleHisory(true)
        getChats({
            robot_id: currentChat.id,
            page_num: 1,
            user_id: 74,
            page_size: 10000
        }).then((res) => {
            if (res.code === 0) {
                let hisChats = JSON.parse(JSON.stringify(history))
                res.result.list.forEach((item) => {
                    let date = item.created_at.split('T')[0] + ' ' + item.created_at.split('T')[1].slice(0, 5)
                    let ask = {
                        date,
                        role: 0,
                        msg: item.question
                    }
                    let answer = {
                        date,
                        role: 1,
                        msg: item.answer
                    }
                    hisChats.push(ask, answer)
                })
                setHistory(hisChats)
                let a = groupedByDate(hisChats, 'date')
                setHistoryGroup(a)
            }
        })
    }

    // 使用reduce进行分组
    const groupedByDate = (array, key) => {
        return array.reduce((acc, currentObj) => {
            // 将日期转换为键（如果需要的话，这里假设已经是格式化的日期字符串）
            let dateKey = currentObj[key].split('T')[0];
            // 如果acc中还没有这个日期，则创建一个新的数组
            if (!acc[dateKey]) {
                acc[dateKey] = [];
            }
            // 将当前对象添加到对应日期的数组中
            acc[dateKey].push(currentObj);
            // 返回累加器（即修改后的acc对象）
            return acc;
        }, {});
    }


    const dialogHtml = (item) => {
        return <>
            {
                item.role === 0 ? <div key={item.date + currentChat.id + 'all'} className="group flex gap-3 w-full flex-row-reverse mt-2">
                    <div className="flex flex-col w-11/12  max-w-fit items-start gap-2">
                        <div className="px-4 py-2 w-full ask">
                            <div className="markdown-body markdown-custom-styles !text-base font-normal">
                                <p>{item.msg}</p>
                            </div>
                        </div>
                    </div>
                    {copyHtml(item.msg)}
                </div>
                    : <>{
                        item.role === 1 ? <div key={item.date + currentChat.id + 'all'} className="group flex gap-3 w-full flex-row mt-2">
                            <div className="flex flex-col w-11/12  max-w-fit items-start gap-2">
                                <div className="px-4 py-2 w-full answer">
                                    <div className="markdown-body markdown-custom-styles !text-base font-normal" dangerouslySetInnerHTML={{ __html: marked(item.msg) }}>
                                    </div>
                                </div>
                            </div>
                            {copyHtml(item.msg)}
                        </div> : <>{loading(item)}</>
                    }</>
            }
        </>
    }

    return (
        <>
            <div className="main">
                <div className="px-[15px] py-3 h-full overflow-hidden" style={{ paddingLeft: '0' }}>
                    <div className="overflow-hidden h-full">
                        <div className="flex flex-col overflow-hidden bg-primary-background h-full rounded-[10px]">
                            <div className="border-b border-solid border-primary-border flex flex-row items-center justify-between gap-2 py-[10px] mx-5">
                                <div className="flex flex-row items-center gap-2">
                                    <img src={currentChat.icon} alt='' className="w-[18px] h-[18px] object-contain rounded-full" />
                                    <span className="font-semibold text-primary-text text-sm cursor-default" data-state="closed">{currentChat.name}</span>
                                </div>
                                <div className="flex flex-row items-center gap-3">
                                    <img src={HistorySvg} alt='' onClick={() => { checkHistory() }} className="w-5 h-5 cursor-pointer" data-state="closed" />
                                    {/* <img src={ShareSvg} alt='' className="w-5 h-5 cursor-pointer" data-state="closed" /> */}
                                    <img src={ClearSvg} alt='' onClick={() => { setVisibleTips(true) }} className="w-5 h-5 cursor-pointer" data-state="closed" />
                                </div>
                            </div>
                            <div id='scrollDiv' className="react-scroll-to-bottom--css-vwhnp-79elbk overflow-auto h-full">
                                <div className="react-scroll-to-bottom--css-vwhnp-1n7m0yu">
                                    <div className="flex flex-col gap-3 h-full mx-5">
                                        {
                                            dialog[currentChat.id] && dialog[currentChat.id]?.log && dialog[currentChat.id]?.log.map((item) => {
                                                return dialogHtml(item)
                                            })
                                        }
                                    </div>
                                </div>
                            </div>
                            <div className="mt-3 flex flex-col mx-5 mb-3">
                                <div className="flex flex-row items-center gap-[5px] mb-3">
                                    <hr className="grow border-primary-border" />
                                </div>
                                <div className="flex flex-row items-center gap-3">
                                    <img style={{ width: '24px', height: '24px' }} src={ShuruIcon} alt='' />
                                    <div className="w-full flex flex-col justify-center">
                                        <textarea
                                            disabled={!sendState}
                                            id="myTextarea"
                                            onKeyDown={bindEnter}
                                            className="resize-none overflow-x-hidden overflow-y-auto  w-full outline-none text-sm text-primary-text bg-transparent scrollbar-thin"
                                            autoComplete="off" name="input" placeholder="Shift+Enter添加换行"
                                            style={{ height: "40px" }}></textarea>
                                    </div>
                                    <div className="flex flex-row items-center gap-[10px] shrink-0">
                                        {
                                            sendState ? <button onClick={() => {
                                                sendMsg()
                                            }} type="submit" className="rounded-full text-base font-medium px-6 py-[5px] text-white">
                                                <div className="send_btn">发送</div>
                                            </button>
                                                :
                                                <button onClick={() => {
                                                    cancelSend()
                                                }} type="submit" className="rounded-full text-base font-medium px-6 py-[5px] text-primary-text">
                                                    <div className="cancel_btn">停止</div>
                                                </button>
                                        }
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            <Modal
                className={'history_modal'}
                title={<p>与<span style={{ fontWeight: 'bold' }}>{currentChat.name}</span>的聊天记录</p>}
                visible={visibleHisory}
                footer={null}
                onCancel={() => {
                    setVisibleHisory(false);
                }}
                style={{ width: '1000px', height: '600px', background: '#F8F8F8', borderRadius: '20px' }}
            >
                <div className="react-scroll-to-bottom--css-vwhnp-1n7m0yu history_content">
                    <div className='rounded-[10px] w-full flex flex-row text-primary-text search_history'>
                        <div className='icon_search_box'>
                            <IconSearch className='icon_search' />
                        </div>
                        <Input className='search_input' onPressEnter={(e) => {
                            console.log(e.target.value)
                        }} style={{ width: '100%' }} allowClear placeholder='请输入聊天内容进行搜索' />
                    </div>
                    <div className="flex flex-col gap-3 h-full history_content_scroll">
                        {
                            Object.keys(historyGroup).map((key) => {
                                return <div className='history_item'>
                                    <p className='date_history'>{key}</p>
                                    {
                                        historyGroup[key].map((item) => {
                                            return dialogHtml(item)
                                        })
                                    }
                                </div>
                            })
                        }
                    </div>
                </div>
            </Modal>


            <Modal
                className="xzy_modal"
                style={{
                    width: '260px',
                    height: '176px',
                    border: '1px solid #D6D6D6',
                    borderRadius: '20px'
                }}
                title='温馨提示'
                visible={visibleTips}
                autoFocus={true}
                onCancel={() => setVisibleTips(false)}
                footer={<div className='btns'>
                    <div className='butn cancel' onClick={() => setVisibleTips(false)}>取消</div>
                    <div className='butn confirm' onClick={() => {
                        setVisibleTips(false)
                        clearHistory()
                    }}>确定</div>
                </div>}
            >
                <div className='tipscontent'>
                    是否确定删除聊天记录
                </div>
            </Modal>
        </>
    );
}

export default Home;
